<template>
  <view class="page">
    <!-- 使用 z-paging 实现下拉刷新和上拉加载 -->
    <z-paging
      ref="paging"
      v-model="analysisList"
      :fixed="true"
      safe-area-inset-bottom
      :default-page-size="10"
      :auto-show-back-to-top="true"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      @query="queryList"
    >
      <!-- 列表渲染 -->
      <view class="list-container">
        <view
          v-for="(item, index) in analysisList"
          :key="item.id || index"
          class="analysis-card"
          @click="expandCard(index)"
        >
          <!-- 卡片头部 -->
          <view class="card-header">
            <view class="header-left">
              <view class="title-row">
                <view class="ai-badge">
                  <text class="badge-text">AI</text>
                </view>
                <text class="card-title">{{ item.title }}</text>
              </view>
              <view class="time-row">
                <uv-icon name="clock" size="14" color="#909399"></uv-icon>
                <text class="time-text">{{ formatTime(item.executeTime) }}</text>
              </view>
            </view>
            <view class="expand-icon" :class="{ expanded: expandedIndex === index }">
              <uv-icon name="arrow-down" size="20" color="#909399"></uv-icon>
            </view>
          </view>

          <!-- 卡片内容（展开时显示） -->
          <view v-if="expandedIndex === index" class="card-content">
            <view class="content-divider"></view>
            <view class="analysis-content">
              <!-- 显示 message 字段（如果有） -->
              <view v-if="item.message" class="message-section">
                <text class="message-label">分析信息：</text>
                <text class="message-text">{{ formatMessage(item.message) }}</text>
              </view>
              <!-- 显示 content 字段（如果有） -->
              <view v-if="item.content" class="content-section selectable-content">
                <rich-text :nodes="markdownToHtmlForParse(item.content)"></rich-text>
              </view>
              <!-- 如果都没有，显示提示 -->
              <view v-if="!item.message && !item.content" class="no-content">
                <text>暂无详细内容</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <template #empty>
        <view class="empty-state">
          <view class="empty-icon">
            <image
              class="empty-img"
              src="/static/images/home/robot.png"
              mode="aspectFit"
            />
          </view>
          <text class="empty-text">暂无AI分析数据</text>
          <text class="empty-desc">AI小智正在努力分析中，敬请期待</text>
        </view>
      </template>
    </z-paging>
  </view>
</template>

<script>
import { getAiAnalysis } from '@/api/ai'
import { formatAiAnalysisToMarkdown } from '@/utils/aiAnalysisFormatter'

export default {
  data() {
    const sys = uni.getSystemInfoSync()
    const statusBarPx = sys.statusBarHeight || 0

    return {
      statusBarPx,
      analysisList: [],
      allAnalysisList: [], // 缓存所有数据（用于本地分页）
      expandedIndex: -1, // 当前展开的卡片索引
      isLoading: false,
      isFirstLoad: true // 是否首次加载
    }
  },

  onUnload() {
    // 页面卸载时清除缓存，避免占用存储空间
    try {
      uni.removeStorageSync('current_ai_analysis')
      console.log('已清除AI分析详情缓存')
    } catch (error) {
      console.error('清除缓存失败:', error)
    }
  },

  onBackPress() {
    // 拦截返回事件，跳转到首页
    this.goBack()
    return true // 返回 true 表示拦截默认返回行为
  },

  methods: {
    /**
     * z-paging 查询数据方法（实现本地分页）
     * @param {Number} pageNo - 页码
     * @param {Number} pageSize - 每页数量
     */
    async queryList(pageNo, pageSize) {
      try {
        console.log('请求AI分析数据（本地分页）:', { pageNo, pageSize })

        this.isLoading = true

        // 下拉刷新时（pageNo === 1），清空缓存重新获取
        if (pageNo === 1 && !this.isFirstLoad) {
          console.log('下拉刷新，清空缓存')
          this.allAnalysisList = []
          this.isFirstLoad = true
          this.expandedIndex = -1 // 重置展开状态
        }

        // 如果是首次加载或缓存为空，获取所有数据
        if (this.isFirstLoad) {
          const response = await getAiAnalysis()

          console.log('API 响应:', response)

          if (response.code === 200) {
            // 处理数据结构：response.data 是数组
            const records = response.data || []

            // 格式化所有数据并缓存
            this.allAnalysisList = records.map((analysis, index) => ({
              id: analysis.id || `ai-${index}`,
              title: analysis.title || '未命名分析',
              content: analysis.content || '',
              executeTime: analysis.executeTime || '',
              message: analysis.message || '',
              timestamp: analysis.timestamp || 0
            }))

            console.log('AI分析数据加载成功，共', this.allAnalysisList.length, '条')
            console.log('数据详情:', this.allAnalysisList)
            this.isFirstLoad = false
          } else {
            throw new Error(response.message || '加载失败')
          }
        }

        // 本地分页：从缓存中获取当前页数据
        const startIndex = (pageNo - 1) * pageSize
        const endIndex = startIndex + pageSize
        const pageData = this.allAnalysisList.slice(startIndex, endIndex)

        console.log(`第${pageNo}页数据:`, {
          startIndex,
          endIndex,
          pageDataLength: pageData.length,
          totalLength: this.allAnalysisList.length
        })

        this.isLoading = false

        // 完成加载
        this.$refs.paging.complete(pageData)
      } catch (error) {
        console.error('加载AI分析数据失败:', error)

        this.isLoading = false

        // 加载失败
        this.$refs.paging.complete(false)

        uni.showToast({
          title: error.message || '加载失败，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    },

    /**
     * 展开/收起卡片
     */
    expandCard(index) {
      if (this.expandedIndex === index) {
        this.expandedIndex = -1
      } else {
        this.expandedIndex = index
      }
    },

    /**
     * 格式化时间
     */
    formatTime(timeStr) {
      if (!timeStr) return ''

      try {
        const time = new Date(timeStr)
        const now = new Date()
        const diff = now - time

        // 计算时间差
        const minute = 60 * 1000
        const hour = 60 * minute
        const day = 24 * hour

        // 1分钟内
        if (diff < minute) {
          return '刚刚'
        }
        // 1小时内
        if (diff < hour) {
          return `${Math.floor(diff / minute)}分钟前`
        }
        // 24小时内
        if (diff < day) {
          return `${Math.floor(diff / hour)}小时前`
        }
        // 7天内
        if (diff < 7 * day) {
          return `${Math.floor(diff / day)}天前`
        }

        // 超过7天，显示完整日期
        const year = time.getFullYear()
        const month = String(time.getMonth() + 1).padStart(2, '0')
        const dayNum = String(time.getDate()).padStart(2, '0')
        const hourNum = String(time.getHours()).padStart(2, '0')
        const minuteNum = String(time.getMinutes()).padStart(2, '0')

        // 如果是今年，不显示年份
        if (year === now.getFullYear()) {
          return `${month}-${dayNum} ${hourNum}:${minuteNum}`
        }

        return `${year}-${month}-${dayNum} ${hourNum}:${minuteNum}`
      } catch (error) {
        return timeStr
      }
    },

    /**
     * 返回首页
     */
    goBack() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },

    /**
     * 格式化消息内容（处理 Markdown）
     */
    formatMessage(content) {
      if (!content) return ''
      return formatAiAnalysisToMarkdown(content)
    },

    /**
     * 将 Markdown 转换为 rich-text 支持的 HTML
     * @param {string} markdown - Markdown 内容
     * @returns {string} HTML 内容
     */
    markdownToHtmlForParse(markdown) {
      if (!markdown) return ''

      let html = markdown

      // 转义 HTML 特殊字符
      const escapeHtml = (text) => {
        if (!text) return ''
        const map = {
          '&': '&amp;',
          '<': '&lt;',
          '>': '&gt;',
          '"': '&quot;',
          "'": '&#039;'
        }
        return text.replace(/[&<>"']/g, m => map[m])
      }

      html = escapeHtml(html)

      // 移除 # 号（标题标记），只保留文本内容
      html = html.replace(/(?:^|\n)#{1,6}\s+(.+?)(?=\n|$)/gm, '\n$1')

      // 粗体处理
      html = html.replace(/\*\*(.+?)\*\*/g, '<strong style="color: #00d4aa; font-weight: 700;">$1</strong>')

      // 列表处理 - 使用更小的字体和间距
      html = html.replace(/(?:^|\n)-\s+(.+?)(?=\n|$)/gm, '\n<div style="margin-left: 20rpx; margin-top: 8rpx; line-height: 1.6; color: #333; font-size: 28rpx;">• $1</div>')

      // 有序列表处理
      html = html.replace(/(?:^|\n)(\d+)\.\s+(.+?)(?=\n|$)/gm, '\n<div style="margin-left: 20rpx; margin-top: 8rpx; line-height: 1.6; color: #333; font-size: 28rpx;">$1. $2</div>')

      // 引用处理 - 使用更小的字体
      html = html.replace(/(?:^|\n)&gt;\s*(.+?)(?=\n|$)/gm, '\n<div style="border-left: 4rpx solid #00d4aa; padding-left: 16rpx; margin: 12rpx 0; color: #666; font-style: italic; font-size: 26rpx; line-height: 1.6; background: rgba(0, 212, 170, 0.05);">$1</div>')

      // 代码块处理
      html = html.replace(/```([\s\S]*?)```/g, '<div style="background: #f5f7fa; border-radius: 8rpx; padding: 16rpx; margin: 12rpx 0; overflow-x: auto; font-family: \'Courier New\', monospace; font-size: 24rpx; color: #333; line-height: 1.5; user-select: text; -webkit-user-select: text;"><code>$1</code></div>')

      // 行内代码处理
      html = html.replace(/`([^`]+)`/g, '<code style="padding: 4rpx 8rpx; background: #f5f7fa; border-radius: 4rpx; font-family: \'Courier New\', monospace; font-size: 26rpx; color: #e83e8c; user-select: text; -webkit-user-select: text;">$1</code>')

      // 段落处理 - 双换行表示新段落
      html = html.replace(/\n\n/g, '</p><p>')

      // 单换行处理 - 保留为换行
      html = html.replace(/\n/g, '<br/>')

      // 包裹段落 - 添加文字选择支持
      if (!html.startsWith('<')) {
        html = `<p style="margin: 0 0 16rpx 0; line-height: 1.6; color: #333; font-size: 28rpx; user-select: text; -webkit-user-select: text; white-space: pre-wrap; word-break: break-word;">${html}</p>`
      }

      return html
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
}

/* 列表容器 */
.list-container {
  padding: 24rpx;
}

/* 分析卡片 */
.analysis-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  border: 1rpx solid #f0f0f0;
  border: 1px solid #f0f3f8;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }

  &:last-child {
    margin-bottom: 0;
  }
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16rpx;
}

.header-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

/* 标题行 */
.title-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

/* AI 徽章 */
.ai-badge {
  flex-shrink: 0;
  padding: 4rpx 12rpx;
  background: linear-gradient(135deg, #00d4aa 0%, #00b894 100%);
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 212, 170, 0.2);
}

.badge-text {
  font-size: 20rpx;
  font-weight: 700;
  color: #ffffff;
  letter-spacing: 1rpx;
}

/* 卡片标题 */
.card-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: 700;
  color: #303133;
  line-height: 1.4;
  word-break: break-word;
}

/* 时间行 */
.time-row {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.time-text {
  font-size: 24rpx;
  color: #909399;
}

/* 展开图标 */
.expand-icon {
  flex-shrink: 0;
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 50%;
  transition: all 0.3s ease;

  &.expanded {
    transform: rotate(180deg);
    background: #e8f8f5;
  }
}

/* 卡片内容 */
.card-content {
  margin-top: 20rpx;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 内容分隔线 */
.content-divider {
  height: 1rpx;
  background: linear-gradient(90deg,
    rgba(0, 212, 170, 0) 0%,
    rgba(0, 212, 170, 0.2) 50%,
    rgba(0, 212, 170, 0) 100%
  );
  margin-bottom: 20rpx;
}

/* 正文内容 */
.analysis-content {
  font-size: 28rpx;
  color: #606266;
  line-height: 1.8;
  word-break: break-word;
  padding: 0 8rpx;
}

/* 分析信息部分 */
.message-section {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  padding: 16rpx;
  background: linear-gradient(135deg, rgba(0, 212, 170, 0.05) 0%, rgba(0, 184, 148, 0.05) 100%);
  border-left: 4rpx solid #00d4aa;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.message-label {
  font-size: 24rpx;
  font-weight: 600;
  color: #00d4aa;
}

.message-text {
  font-size: 28rpx;
  color: #303133;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 内容部分 */
.content-section {
  margin-top: 16rpx;
  user-select: text;
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
}

/* 可选择的内容 */
.selectable-content {
  word-break: break-word;
  white-space: pre-wrap;
}

/* 无内容提示 */
.no-content {
  padding: 32rpx 16rpx;
  text-align: center;
  color: #909399;
  font-size: 28rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  min-height: 60vh;
}

.empty-icon {
  margin-bottom: 32rpx;
}

.empty-img {
  width: 240rpx;
  height: 240rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #909399;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #c0c4cc;
  text-align: center;
  line-height: 1.6;
}
</style>

